package com.boot.springboot.component.qrcode.service;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.boot.springboot.component.qrcode.dao.SUserTokenMapper;
import com.boot.springboot.component.qrcode.domain.SUserToken;
import com.boot.springboot.config.websocket.WebSocketServer;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author luowenjie
 * @since 2021/11/24 18:10
 */
@Service
public class SUserTokenService {

    @Autowired
    SUserTokenMapper sUserTokenMapper;

    public String createQrImg(){
        String uuid = IdUtil.randomUUID();
        SUserToken sUserToken = new SUserToken();
        sUserToken.setUuid(uuid);
        sUserToken.setCreateTime(new Date());
        sUserTokenMapper.insertSelective(sUserToken);
        return uuid;
    }

    public String bindUserIdAndToken(Integer userId, String token,Integer projId) throws Exception {

        SUserToken sUserToken = new SUserToken();
        sUserToken = sUserTokenMapper.selectByUuid(token);

        if(null == sUserToken){
            throw  new Exception("错误的请求！");
        }

        Date createDate = new Date(sUserToken.getCreateTime().getTime() + (1000 * 60 * 10));
        Date nowDate = new Date();
        if(nowDate.getTime() > createDate.getTime()){//当前时间大于校验时间

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code",500);
            jsonObject.put("msg","二维码失效！");
            sUserToken.setState(Byte.valueOf("1"));
            int i = sUserTokenMapper.updateByPrimaryKeySelective(sUserToken);
            WebSocketServer.sendInfo(jsonObject.toJSONString(),token);

            throw  new Exception("二维码失效！");
        }

        sUserToken.setLoginTime(new Date());
        sUserToken.setUserId(userId);

        int i = sUserTokenMapper.updateByPrimaryKeySelective(sUserToken);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code",200);
        jsonObject.put("msg","ok");
        jsonObject.put("userId",userId);
        if(projId!=null){
            jsonObject.put("projId",projId);
        }
        WebSocketServer.sendInfo(jsonObject.toJSONString(),token);

        if(i > 0 ){
            return null;
        }else{
            throw  new Exception("服务器异常！");
        }
    }

}
